package com.ht.modules.system.online.cgform.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ht.api.ISysBaseAPI;
import com.ht.entity.DictModel;
import com.ht.entity.Result;
import com.ht.modules.system.online.cgform.entity.OnlCgformButton;
import com.ht.modules.system.online.cgform.entity.OnlCgformEnhanceJs;
import com.ht.modules.system.online.cgform.entity.OnlCgformField;
import com.ht.modules.system.online.cgform.entity.OnlCgformHead;
import com.ht.modules.system.online.cgform.model.OnlCgformModel;
import com.ht.modules.system.online.cgform.model.OnlGenerateModel;
import com.ht.modules.system.online.cgform.service.IOnlCgformFieldService;
import com.ht.modules.system.online.cgform.service.IOnlCgformHeadService;
import com.ht.modules.system.online.cgform.util.CgformUtil;
import com.ht.modules.system.online.config.util.DbTableUtil;
import com.ht.utils.oConvertUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
@RequestMapping({"/online/cgform/api"})
public class OnlCgformApiController {
    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;
    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    public OnlCgformApiController() {
    }

    @PostMapping({"/addAll"})
    public Result<?> addAll(@RequestBody OnlCgformModel model) {
        try {
//            String tbname = model.getHead().getTableName();
//            return DbTableUtil.judgeTableIsExit(tbname) ? Result.error("数据库表[" + tbname + "]已存在,请从数据库导入表单") : this.onlCgformHeadService.addAll(model);
            //修改：前端验证表名在默认库中不重复即可
            return this.onlCgformHeadService.addAll(model);
        } catch (Exception var3) {
            log.error("OnlCgformApiController.addAll()发生异常：" + var3.getMessage());
            return Result.error("操作失败");
        }
    }

    @PutMapping({"/editAll"})
    public Result<?> editAll(@RequestBody OnlCgformModel model) {
        try {
            return this.onlCgformHeadService.editAll(model);
        } catch (Exception var3) {
            log.error("OnlCgformApiController.editAll()发生异常：" + var3.getMessage());
            return Result.error("操作失败");
        }
    }

    @GetMapping({"/getColumns/{code}"})
    public Result<Map<String, Object>> getColumns(@PathVariable("code") String code) {
        Result<Map<String, Object>> result = new Result<>();
        OnlCgformHead head = this.onlCgformHeadService.getById(code);
        if (head == null) {
            result.error500("实体不存在");
            return result;
        } else {
            LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<>();
            query.eq(OnlCgformField::getCgformHeadId, code);
            query.eq(OnlCgformField::getIsShowList, 1);
            query.orderByAsc(OnlCgformField::getOrderNum);
            List<OnlCgformField> fieldList = this.onlCgformFieldService.list(query);
            List<String> list = this.onlCgformFieldService.selectOnlineHideColumns(head.getTableName());
            List<Map<String, Object>> columns = new ArrayList<>();
            Map<String, Object> dictOptions = new HashMap<>();
            Iterator<?> var9 = fieldList.iterator();
            while (true) {
                OnlCgformField item;
                String dbFieldName;
                do {
                    do {
                        if (!var9.hasNext()) {
                            Map<String, Object> info = new HashMap<>();
                            info.put("columns", columns);
                            info.put("dictOptions", dictOptions);
                            info.put("formTemplate", head.getFormTemplate());
                            info.put("description", head.getTableTxt());
                            info.put("currentTableName", head.getTableName());
                            List<OnlCgformButton> cgButtonList = this.onlCgformHeadService.queryButtonList(code, true);
                            List<OnlCgformButton> cgFinalBtnList = new ArrayList<>();
                            for (OnlCgformButton onlCgformButton : cgButtonList) {
                                if (!list.contains(onlCgformButton.getButtonCode())) {
                                    cgFinalBtnList.add(onlCgformButton);
                                }
                            }
                            info.put("cgButtonList", cgFinalBtnList);
                            OnlCgformEnhanceJs enhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "list");
                            if (enhanceJs != null && oConvertUtils.isNotEmpty(enhanceJs.getCgJs())) {
                                info.put("enhanceJs", CgformUtil.overwriteJs(enhanceJs.getCgJs(), cgButtonList));
                            }
                            info.put("hideColumns", list);
                            result.setResult(info);
                            return result;
                        }

                        item = (OnlCgformField) var9.next();
                        dbFieldName = item.getDbFieldName();
                    } while ("id".equals(dbFieldName));
                } while (list.contains(dbFieldName));

                Map<String, Object> column = new HashMap<>(3);
                column.put("title", item.getDbFieldTxt());
                column.put("dataIndex", dbFieldName);
                column.put("align", "center");
                String dictCode = item.getDictField();
                if (oConvertUtils.isNotEmpty(dictCode) && !"popup".equals(item.getFieldShowType())) {
                    List<DictModel> ls = new ArrayList<>();
                    if (oConvertUtils.isNotEmpty(item.getDictTable())) {
                        ls = this.sysBaseAPI.queryTableDictItemsByCode(item.getDictTable(), item.getDictText(), dictCode);
                    } else if (oConvertUtils.isNotEmpty(item.getDictField())) {
                        ls = this.sysBaseAPI.queryDictItemsByCode(dictCode);
                    }

                    dictOptions.put(dbFieldName, ls);
                    column.put("customRender", dbFieldName);
                }

                if ("sel_depart".equals(item.getFieldShowType())) {
                    List<DictModel> ls = this.sysBaseAPI.queryAllDepartBackDictModel();
                    dictOptions.put(dbFieldName, ls);
                    column.put("customRender", dbFieldName);
                }

                String view = item.getFieldShowType();
                JSONObject scopedSlots;
                if (view.contains("file")) {
                    scopedSlots = new JSONObject();
                    scopedSlots.put("customRender", "fileSlot");
                    column.put("scopedSlots", scopedSlots);
                } else if (view.contains("image")) {
                    scopedSlots = new JSONObject();
                    scopedSlots.put("customRender", "imgSlot");
                    column.put("scopedSlots", scopedSlots);
                } else if (view.contains("editor")) {
                    scopedSlots = new JSONObject();
                    scopedSlots.put("customRender", "htmlSlot");
                    column.put("scopedSlots", scopedSlots);
                } else if ("date".equals(view)) {
                    scopedSlots = new JSONObject();
                    scopedSlots.put("customRender", "dateSlot");
                    column.put("scopedSlots", scopedSlots);
                }

                String dbtype = item.getDbType();
                if ("int".equals(dbtype) || "double".equals(dbtype) || "BigDecimal".equals(dbtype) || "Date".equals(dbtype)) {
                    column.put("sorter", true);
                }

                columns.add(column);
            }
        }
    }

    @GetMapping({"/getData/{code}"})
    public Result<Map<String, Object>> getData(@PathVariable("code") String code, HttpServletRequest request) {
        Result<Map<String, Object>> result = new Result<>();
        OnlCgformHead head = this.onlCgformHeadService.getById(code);
        if (head == null) {
            result.error500("实体不存在");
        } else {
            try {
                String tableName = head.getTableName();
                Map<String, Object> params = CgformUtil.getParameterMap(request);
                Map<String, Object> page = this.onlCgformFieldService.queryAutolistPage(tableName, code, params);
                result.setResult(page);
            } catch (Exception var8) {
                log.error(var8.getMessage(), var8);
                result.error500("数据库查询失败" + var8.getMessage());
            }
        }
        return result;
    }

    @GetMapping({"/getFormItem/{code}"})
    public Result<?> getFormItem(@PathVariable("code") String code) {
        OnlCgformHead head = this.onlCgformHeadService.getById(code);
        if (head == null) {
            return Result.error("表不存在");
        }
        Result<JSONObject> result = new Result<>();
        JSONObject obj = new JSONObject();
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        List<OnlCgformField> fieldList = this.onlCgformFieldService.queryAvailableFields(head.getId(), head.getTableName(), false);
        List<String> disabledFieldNameList = this.onlCgformFieldService.queryDisabledFields(head.getTableName());
        CgformUtil.overwriteJs(onlCgformEnhanceJs, head.getTableName(), fieldList, true);
        JSONObject schema = CgformUtil.getJsonSchemaByCgformFieldList(fieldList, disabledFieldNameList);
        if (head.getTableType() == 2) {
            String subTableStr = head.getSubTableStr();
            if (oConvertUtils.isNotEmpty(subTableStr)) {
                String[] subTableArray = subTableStr.split(",");
                for (String subTable : subTableArray) {
                    OnlCgformHead tempTable = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTable));
                    if (tempTable != null) {
                        List<OnlCgformField> subFieldList = this.onlCgformFieldService.queryAvailableFields(tempTable.getId(), tempTable.getTableName(), false);
                        CgformUtil.overwriteJs(onlCgformEnhanceJs, tempTable.getTableName(), subFieldList);
                        JSONObject subJson = new JSONObject();
                        subJson.put("columns", CgformUtil.getJEditableTableColumnsJson(subFieldList));
                        subJson.put("describe", tempTable.getTableTxt());
                        subJson.put("key", tempTable.getTableName());
                        subJson.put("view", "tab");
                        schema.getJSONObject("properties").put(tempTable.getTableName(), subJson);
                    }
                }
            }
        }
        obj.put("schema", schema);
        obj.put("head", head);
        List<OnlCgformButton> cgButtonList = this.onlCgformHeadService.queryButtonList(code, false);
        if (cgButtonList != null && !cgButtonList.isEmpty()) {
            obj.put("cgButtonList", cgButtonList);
        }
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            obj.put("enhanceJs", CgformUtil.returnEnhanceJsClass(CgformUtil.overwriteJsByButtonStyle(onlCgformEnhanceJs.getCgJs(), cgButtonList)));
        }
        result.setResult(obj);
        return result;
    }

    @GetMapping({"/getFormItemBytbname/{table}"})
    public Result<?> getFormItemBytTableName(@PathVariable("table") String table) {
        Result<JSONObject> result = new Result<>();
        LambdaQueryWrapper<OnlCgformHead> query = new LambdaQueryWrapper<>();
        query.eq(OnlCgformHead::getTableName, table);
        OnlCgformHead head = this.onlCgformHeadService.getOne(query);
        if (head == null) {
            Result.error("表不存在");
        }

        JSONObject obj = new JSONObject();
        obj.put("schema", this.onlCgformHeadService.queryFormItem(head));
        obj.put("head", head);
        result.setResult(obj);
        return result;
    }

    @GetMapping({"/getEnhanceJs/{code}"})
    public Result<?> getEnhanceJs(@PathVariable("code") String code, HttpServletRequest request) {
        String enhanceJsStr = "";
        OnlCgformEnhanceJs enhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        if (enhanceJs != null && oConvertUtils.isNotEmpty(enhanceJs.getCgJs())) {
            enhanceJsStr = CgformUtil.overwriteJs(enhanceJs.getCgJs(), null);
        }

        return Result.ok(enhanceJsStr);
    }

    @GetMapping({"/form/{code}/{id}"})
    public Result<?> getFormData(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            Map<String, Object> map = this.onlCgformHeadService.queryManyFormData(code, id);
            return Result.ok(CgformUtil.transLowerCaseMapKey(map));
        } catch (Exception var4) {
            log.error("Online表单查询异常：" + var4.getMessage(), var4);
            return Result.error("查询失败");
        }
    }

    @PostMapping({"/form/{code}"})
    public Result<?> formAdd(@PathVariable("code") String code, @RequestBody JSONObject jsonObject) {
        try {
            this.onlCgformHeadService.saveManyFormData(code, jsonObject);
        } catch (Exception var4) {
            log.error("OnlCgformApiController.formAdd()发生异常：" + var4.getMessage());
            return Result.error("保存失败");
        }

        return Result.ok("保存成功!");
    }

    @PutMapping({"/form/{code}"})
    public Result<?> formEdit(@PathVariable("code") String code, @RequestBody JSONObject jsonObject) {
        try {
            this.onlCgformHeadService.editManyFormData(code, jsonObject);
        } catch (Exception var4) {
            log.error("OnlCgformApiController.formEdit()发生异常：" + var4.getMessage());
            return Result.error("修改失败");
        }

        return Result.ok("修改成功!");
    }

    @DeleteMapping({"/form/{code}/{id}"})
    public Result<?> formEdit(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            if (id.indexOf(",") > 0) {
                OnlCgformHead head = this.onlCgformHeadService.getById(code);
                if (head == null) {
                    return Result.error("实体不存在");
                }

                String tbname = head.getTableName();
                this.onlCgformFieldService.deleteAutoList(tbname, id);
            } else {
                this.onlCgformHeadService.deleteOneTableInfo(code, id);
            }
        } catch (Exception var5) {
            log.error("OnlCgformApiController.formEdit()发生异常：" + var5.getMessage());
            return Result.error("删除失败");
        }

        return Result.ok("删除成功!");
    }

    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> getQueryInfo(@PathVariable("code") String code) {
        try {
            List<Map<String, String>> list = this.onlCgformFieldService.getAutoListQueryInfo(code);
            return Result.ok(list);
        } catch (Exception var3) {
            log.error("OnlCgformApiController.getQueryInfo()发生异常：" + var3.getMessage());
            return Result.error("查询失败");
        }
    }

    @PostMapping({"/doDbSynch/{code}/{synMethod}"})
    public Result<?> doDbSynch(@PathVariable("code") String code, @PathVariable("synMethod") String synMethod) {
        try {
            this.onlCgformHeadService.doDbSynch(code, synMethod);
        } catch (Exception e) {
            log.error("OnlCgformApiController.doDbSynch()发生异常：{}", e.getMessage(), e);
            return Result.error("同步数据库失败");
        }
        return Result.ok("同步数据库成功!");
    }

    @PostMapping({"/doButton"})
    public Result<?> doButton(@RequestBody JSONObject json) {
        String formId = json.getString("formId");
        String dataId = json.getString("dataId");
        String buttonCode = json.getString("buttonCode");

        try {
            this.onlCgformHeadService.executeCustomerButton(buttonCode, formId, dataId);
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return Result.error("执行失败!");
        }

        return Result.ok("执行成功!");
    }

    @GetMapping({"/checkOnlyTable"})
    public Result<?> checkOnlyTable(@RequestParam("tbname") String tbname, @RequestParam("id") String id) {
        if (oConvertUtils.isEmpty(id)) {
            if (DbTableUtil.judgeTableIsExit(tbname)) {
                return Result.ok(-1);
            }
        } else {
            OnlCgformHead head = this.onlCgformHeadService.getById(id);
            if (!tbname.equals(head.getTableName()) && DbTableUtil.judgeTableIsExit(tbname)) {
                return Result.ok(-1);
            }
        }

        return Result.ok(1);
    }

    @PostMapping({"/codeGenerate"})
    public Result<?> codeGenerate(@RequestBody OnlGenerateModel onlGenerateModel) {
        try {
            this.onlCgformHeadService.generateCode(onlGenerateModel);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("生成失败！");
        }
        return Result.ok(1);
    }
}
